package net.hmr_radio.hmrbot.controller.twitter;

import net.hmr_radio.hmrbot.controller.BaseController;
import net.hmr_radio.hmrbot.util.AssertionUtil;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.slim3.controller.Navigation;

import twitter4j.Twitter;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class CallbackController extends BaseController {

    private Log log = LogFactory.getLog(CallbackController.class);

    @Override
    public Navigation run() throws Exception {

        Twitter twitter = sessionScope("twitter");
        RequestToken requestToken = sessionScope("requestToken");
        String destinationURL = sessionScope("destinationURL");

        removeSessionScope("twitter");
        removeSessionScope("requestToken");
        removeSessionScope("destinationURL");

        AssertionUtil.nullCheck(twitter, requestToken, destinationURL);

        if (asString("oauth_verifier") == null) {
            return forward(destinationURL);
        }
        AccessToken accessToken =
            twitter.getOAuthAccessToken(
                requestToken,
                asString("oauth_verifier"));

        requestScope("accessToken", accessToken.getToken());
        requestScope("accessTokenSecret", accessToken.getTokenSecret());
        log.info("accessToken = " + accessToken.getToken());
        log.info("accessTokenSecret = " + accessToken.getTokenSecret());

        return forward(destinationURL);
    }
}
